﻿using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Yc.QrCodeLib;
using Yc.QrCodeLib.Data;

namespace QRTool
{
    public partial class Form_QR : Form
    {
        public static String RENAME = "";  // 设置生成的二维码图像名称

        public Form_QR()
        {
            InitializeComponent();
        }


        #region Form_QR相关事件逻辑

        bool update = true;
        /// <summary>
        /// url地址变动，更新二维码显示
        /// </summary>
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (update)
            {
                String url = textBox1.Text;
                if (!url.Equals(""))
                {
                    Bitmap pic = ToQR(url);
                    pictureBox1.Image = pic;
                }
            }
        }

        private void panel1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))    //判断拖来的是否是文件  
                e.Effect = DragDropEffects.Link;                //是则将拖动源中的数据连接到控件  
            else e.Effect = DragDropEffects.None;
        }

        /// <summary>
        /// 二维码图像变动，解析url地址到输入框
        /// </summary>
        private void panel1_DragDrop(object sender, DragEventArgs e)
        {
            Array files = (System.Array)e.Data.GetData(DataFormats.FileDrop);//将拖来的数据转化为数组存储
            foreach (object I in files)
            {
                try
                {
                    string str = I.ToString();
                    Image pic = Bitmap.FromFile(str);
                    pictureBox1.Image = pic;

                    // 解析二维码图像
                    update = false;
                    String code = ToCode(new Bitmap(pic));
                    textBox1.Text = code;
                    update = true;

                    break;
                }
                catch (Exception ex) { }
            }
        }

        /// <summary>
        /// 保存图像
        /// </summary>
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            linkLabel1.Visible = true;
            if (pictureBox1.Image != null)
            {
                Bitmap pic = new Bitmap(pictureBox1.Image);

                String filepath = Save(pic);
                linkLabel1.Text = "二维码已保存：" + filepath;
            }
            else linkLabel1.Text = "";
        }

        /// <summary>
        /// 在文件浏览器中显示已保存的二维码图像文件
        /// </summary>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            String dir = curDir() + "QR\\";
            String name = linkLabel1.Text.Substring("二维码已保存：".Length);
            ShowFileInExplorer(dir + name);

            linkLabel1.Visible = false;
        }

        private void 跳转二维码地址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!textBox1.Text.Equals("")) System.Diagnostics.Process.Start(textBox1.Text);
        }

        #endregion


        #region 二维码功能函数

        /// <summary>
        /// 获取链接地址对应的二维码图像
        /// </summary>
        public static Bitmap ToQR(String url)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode qrCode = qrEncoder.Encode(url);

            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
            DrawingSize size = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap pic = new Bitmap(size.CodeWidth, size.CodeWidth);
            Graphics g = Graphics.FromImage(pic);

            render.Draw(g, qrCode.Matrix);

            return pic;
        }

        /// <summary>
        /// 将二维码图像转化为编码串
        /// </summary>
        public static string ToCode(Bitmap pic)
        {
            QRCodeDecoder decoder = new QRCodeDecoder();
            String decodedString = decoder.decode(new QRCodeBitmapImage(pic));

            return decodedString;
        }

        # endregion


        #region 其他相关功能函数

        /// <summary>
        /// 保存图像返回文件名
        /// </summary>
        public static String Save(Bitmap pic)
        {
            String path = curDir() + "QR\\";
            checkDir(path);

            String name = DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".png";
            if (!RENAME.Equals("")) name = RENAME;

            Save(pic, path + name);

            return name;
        }

        /// <summary>
        /// 保存图像
        /// </summary>
        public static void Save(Bitmap pic, String filePath)
        {
            if (File.Exists(filePath)) File.Delete(filePath);
            pic.Save(filePath, ImageFormat.Png);
        }

        /// <summary>
        /// 获取当前运行路径
        /// </summary>
        public static string curDir()
        {
            return AppDomain.CurrentDomain.BaseDirectory;
        }

        /// <summary>
        /// 检测目录是否存在，若不存在则创建
        /// </summary>
        public static void checkDir(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        /// <summary>
        /// 在文件浏览器中显示指定的文件
        /// </summary>
        public static void ShowFileInExplorer(String file)
        {
            if (File.Exists(file)) System.Diagnostics.Process.Start("explorer.exe", "/e,/select, " + file);
            else System.Diagnostics.Process.Start("explorer.exe", "/e, " + file);
        }

        #endregion


    }
}
